package cn.crawler.app.task.commons.ext.quartz.job;

import cn.crawler.app.crown.modules.models.CrownConfig;
import cn.crawler.app.crown.modules.models.CrownMatch;
import cn.crawler.app.crown.modules.services.CrownConfigService;
import cn.crawler.app.crown.modules.services.CrownMatchService;
import cn.crawler.app.crown.modules.services.result.MatchResultService;
import cn.crawler.app.sys.modules.services.SysTaskService;
import cn.crawler.framework.base.exceptions.BizException;
import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.quartz.Job;
import org.quartz.JobExecutionContext;

import java.util.List;

/**
 * 获取赛事赛果
 */
@IocBean
public class CrownJobMatchResult implements Job {
    @Inject
    @Reference(retries = 3, timeout = 500000)
    private CrownMatchService matchService;

    @Inject
    @Reference(retries = 3, timeout = 500000)
    private MatchResultService matchResultService;

    @Inject
    @Reference(retries = 0, timeout = 500000)
    private CrownConfigService crownConfigService;


    @Inject
    @Reference
    private SysTaskService sysTaskService;

    private static final Log log = Logs.get();

    @Override
    public void execute(JobExecutionContext context) {
        CrownConfig crownConfig = crownConfigService.syncOne("获取赛果任务");
        if (crownConfig != null) {
            log.info("准备开始赛事赛果爬取:" + crownConfig);
            this.crawler(crownConfig, context);
        }
        String taskId = context.getJobDetail().getKey().getName();
        sysTaskService.update(Chain.make("exeAt", (int) (System.currentTimeMillis() / 1000))
                .add("exeResult", "执行成功"), Cnd.where("id", "=", taskId));
    }

    private synchronized void crawler(CrownConfig crownConfig, JobExecutionContext context) {
        try {
            // 获取系统当前时间
            String endTime = DateFormatUtils.format(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss");
            // 获取未结束的赛事
            Cnd cnd = Cnd.where("dateTime", "<", endTime).and("stage", "!=", "finished")
                    .and("stage", "!=", "other").limit(0, 500);
            List<CrownMatch> list = matchService.query(cnd);
            for (int i = 0; i < list.size(); i++) {
                try {
                    matchResultService.crawler(list.get(i), crownConfig);
                } catch (BizException e) {
                    log.error(e.getRemand());
                }
            }
        } catch (Exception e) {
            log.error("爬赛果定时任务异常" + e.getMessage());
        } finally {
            // 获取账号，判断是否为空，以防账号已经被清除
            crownConfigService.release(crownConfig);
        }
    }

}
